import CryptoJS from 'crypto-js';
import aes from 'crypto-js/aes';
import md5 from 'crypto-js/md5';
import isEmpty from 'lodash/isEmpty';

const getDecrypt = (params, secrets) => {
    let res;
    try {
        res = aes
            .decrypt(params, CryptoJS.enc.Utf8.parse(secrets), {
                iv: CryptoJS.enc.Utf8.parse(secrets),
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            })
            .toString(CryptoJS.enc.Utf8);
    } catch (e) {
        console.error(e);
        console.error('CryptoJS报错 !');
        return params;
    }
    return JSON.parse(res);
};

export default {
    getSign: (timeStamp, apiKeys, params) =>
        md5(`${timeStamp}${apiKeys}${params}`)
            .toString()
            .toUpperCase(),
    encrypt: (data, secrets) =>
        aes
            .encrypt(JSON.stringify(data), CryptoJS.enc.Utf8.parse(secrets), {
                iv: CryptoJS.enc.Utf8.parse(secrets),
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
            })
            .toString(),
    decrypt: (params, secrets, encryption = true) => {
        // encryption === false 不去解密响应报文
        if (typeof params !== 'string' || encryption === false) return params;
        try {
            return params && !isEmpty(params) ? getDecrypt(params, secrets) : params;
        } catch (e) {
            console.log('!!!!!!!!!!!!!!!!params非JSON!!!!!!!!!!!!!!!!!');
            return params;
        }
    }
};
